package cn.cvs.controller;

import cn.cvs.pojo.Supplier;
import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SupplierService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class SupplierController {

    @Autowired
    private SupplierService supplierService;

    // 分页查询供货商信息
    @RequestMapping("/sys/supplier/list")
    public String findByAccountOrRoleId( @RequestParam(value = "querySupCode", required = false) String querySupCode,
                                         @RequestParam(value = "querySupName", required = false) String querySupName,
                                         @RequestParam(defaultValue="1", required = false) Integer pageIndex,
                                         Model model) {
         try {

             // 设置页面大小
             int pageSize = Constants.pageSize;
             //总记录数
             int  totalCount = supplierService.getUserCount("%"+(querySupCode == null ? "":querySupCode)+"%","%"+(querySupName == null ? "":querySupName)+"%");

             PageSupport pages = new PageSupport();
             pages.setCurrentPageNo(pageIndex);
             pages.setPageSize(pageSize);
             pages.setTotalCount(totalCount);
             int totalPageCount = pages.getTotalPageCount();
             //控制首尾页
             if (pageIndex > totalCount){
                 pageIndex = totalPageCount;
             }
             List<Supplier> supplierList = supplierService.findSupplier("%"+(querySupCode == null ? "":querySupCode)+"%","%"+(querySupName == null ? "":querySupName)+"%",pageIndex,pageSize); // 获取所有供货商列表
             model.addAttribute("supplierList", supplierList); // 将供货商列表添加到模型
             model.addAttribute("querySupCode",querySupCode);
             model.addAttribute("querySupName",querySupName);
             model.addAttribute("totalPageCount",totalPageCount);
             model.addAttribute("totalCount",totalCount);
             model.addAttribute("currentPageNo",pageIndex);
             return "supplier/list"; // 返回供货商列表视图
         }catch (Exception e){
             e.printStackTrace();
             return "redirect:/sysError";
         }


    }


    // 查看供货商信息
    @RequestMapping("/sys/supplier/view/{id}")
    public String getByIdOrSupplier(@PathVariable("id") Integer id, Model model) {
        Supplier supplier = supplierService.getByIdOrSupplier(id);
        model.addAttribute("supplier",supplier);

        return "supplier/view"; // 返回查看供货商列表视图
    }



    @RequestMapping("/sys/supplier/simpleList")
    public ResponseEntity<String> role() {
       List<Supplier> supplierList = supplierService.findAllSupplier();
        String data = JSON.toJSONString(supplierList);
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON_UTF8).body(data);
    }


    // 根据编号删除供货商信息

    @RequestMapping(value = "/sys/supplier/del/{id}",produces = "application/json; charset=UTF-8")
    @ResponseBody
    public String deleteSupplier(@PathVariable("id")Integer id, Map<String,Object> map){
        String delResult = null;//请求结果

        try {
            //判断当前供应商是否有商品
            int storageRecordCount = supplierService.supplierCount(id);
            System.out.println(storageRecordCount);
            if (storageRecordCount > 0){
                //如果有商品信息，返回商品数量
                delResult = String.valueOf(storageRecordCount);
            }else
            {
                //如果没有执行删除操作
                int count = supplierService.delSupplier(id);
                delResult = "false";
                if (count > 0){
                    delResult="true";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        map.put("delResult",delResult);
        String data = JSON.toJSONString(map);
        return data;
    }



    // 根据编号查询信息
    @RequestMapping("/sys/supplier/toUpdate/{id}")
    public String getByIdOrSuppliers(@PathVariable("id") Integer id, Model model) {
        Supplier supplier = supplierService.getByIdOrSupplier(id);
        model.addAttribute("supplier",supplier);

        return "supplier/update";
    }

   //修改
   @RequestMapping("/sys/supplier/update")
   public String updateSupplier(Supplier supplier,HttpSession session) {
        // 修改人id
       supplier.setUpdatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());// 获取创建人id
        // 修改时间
       supplier.setUpdatedTime(new Date());

     int  count = supplierService.updateSupplier(supplier);

     if ( count > 0){
         return "redirect:/sys/supplier/list";
     }
       return "supplier/update";

   }

    // 跳转添加
    @RequestMapping("/sys/supplier/toAdd")
    public  String toAdd(){
        return "supplier/add";
    }

    //获取上传文件
    private static  final Logger logger = LoggerFactory.getLogger("/supplier/add");

    //添加
    @RequestMapping("/sys/supplier/add")
    public String addSysUser(Supplier supplier,
                             HttpSession session,
                             HttpServletRequest request,
                             @RequestParam("licPic")MultipartFile licPic,
                             @RequestParam("codePic")MultipartFile codePic
    ) {
        String companyLicPic = null;  //企业营业执照的存储路径
        String orgCodePic = null; //组织机构代码证的存储路径

        //获取上传文件路径
        String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator +"uploadfiles");
        logger.info("uploadFile path =========== > " + path); //向日志文件中记录上传文件的路径


        // 判断文件是否为空 （企业营业执照）
        if(!licPic.isEmpty()){
            String oldFileName = licPic.getOriginalFilename();
            logger.info("uploadFile oldFileName =========== > " + oldFileName); //向日志文件中记录原文件
            String prefix = FilenameUtils.getExtension(oldFileName); // 原文件后缀
            logger.info("uploadFile prefix =========== > " + prefix); //向日志文件中记录原文件后缀
            int filesize = 5000000; //文件上传大小限制
            // 判断文件大小
            if( licPic.getSize() > filesize){ // 上传文件大小不能超过 500K
                request.setAttribute("uploadFileError","* 上传文件大小不能超过 500K ");
                return "supplier/add";

            } else  if ( prefix.equalsIgnoreCase("jpg") ||
                    prefix.equalsIgnoreCase("png") ||
                    prefix.equalsIgnoreCase("jpeg") ||
                    prefix.equalsIgnoreCase("pneg") ){ // 上传图片格式是否正确
                //System.currentTimeMillis(); 返回当前时间的毫秒数
                // RandomUtils.nextInt(10000000) 生成一个介于0 （包含）和10000000（不包含） 之间的随机数
                //拼接文件名 列如32456789_Personal.jpg
                String fileName  = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
                logger.debug("new fileName =========== > " + licPic.getName()); //记录生成的文件名
                File targetFile = new File(path,fileName); //通过文件路径和文件名创建文件对象
                if(!targetFile.exists()){ //判断文件是否存
                    targetFile.mkdirs();

                }
                //保存文件

                try {
                    licPic.transferTo(targetFile);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                    request.setAttribute("uploadFileError" ," * 上传文件！");
                    return "supplier/add";
                }
                companyLicPic = path + File.separator+fileName;

            } else {
                request.setAttribute("uploadFileError","* 上传图片格式不正确");
                return "supplier/add";
            }

        }

        // 判断文件是否为空 （组织机构代码证）
        if (!codePic.isEmpty()){
            String oldFileName = codePic.getOriginalFilename(); // 原文件名
            logger.info("uploadFile oldFileName =========== > " + oldFileName); //向日志文件中记录原文件名
            String prefix = FilenameUtils.getExtension(oldFileName); // 原文件后缀
            logger.info("uploadFile prefix =====================>" + prefix); //向日志文件中记录原文件后缀
            int filesize = 500000; // 文件上传大小限制

            // 判断文件上传大小
            if (codePic.getSize() > filesize){// 上传文件大小不能超过 500K
                request.setAttribute("uploadFileError","* 上传文件大小不能超过 500K ");
                return "supplier/add";
            } else if ( prefix.equalsIgnoreCase("jpg") ||
                    prefix.equalsIgnoreCase("png") ||
                    prefix.equalsIgnoreCase("jpeg") ||
                    prefix.equalsIgnoreCase("pneg") ){// 上传图片格式是否正确
                //System.currentTimeMillis(); 返回当前时间的毫秒数
                // RandomUtils.nextInt(10000000) 生成一个介于0 （包含）和10000000（不包含） 之间的随机数
                //拼接文件名 列如32456789_Personal.jpg
                String fileName = System.currentTimeMillis() +RandomUtils.nextInt(1000000) + "_Personal.jpg";
                logger.debug("new fileName==========" + codePic.getName()); // 记录生成的文件名
                File targetFile = new File(path,fileName); //通过文件路径和文件名创建文件对象
                if (!targetFile.exists()){// 判断文件是否存在
                    targetFile.mkdirs();
                }

                // 保存文件
                try {
                    codePic.transferTo(targetFile);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                    request.setAttribute("uploadFileError" ,"* 上传失败！");
                    return"/supplier/add";
                }
                orgCodePic = path + File.separator + fileName;

            } else {
                request.setAttribute("uploadFileError","* 上传图片格式不正确");
                return "supplier/add";
            }

        }
        try {
            // 执行添加
            supplier.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());// 获取创建人id
            //设置供应商的企业营业执照地址
            supplier.setCompanyLicPicPath(companyLicPic);
            //设置供应商的组织机构代码证地址
            supplier.setOrgCodePicPath(orgCodePic);
            if ( supplierService.addSupplier(supplier) > 0){ // 判断是否添加成功

                return "redirect:/sys/supplier/list";
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            logger.error("保存用户信息失败");
        }

        return "/supplier/add";
    }



}
